package com.sicong.authentication.controller;

import com.sicong.common.core.enums.ResultEnum;
import com.sicong.common.core.utils.Result;
import com.sicong.common.core.utils.ResultUtil;
import com.sicong.common.security.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    private final TokenUtil tokenUtil;

    private final UserDetailsService userDetailsService;

    private final PasswordEncoder passwordEncoder;

    private final CacheManager cacheManager;

    @Autowired
    public LoginController(TokenUtil tokenUtil, UserDetailsService userDetailsService,
                           PasswordEncoder passwordEncoder, CacheManager cacheManager) {
        this.tokenUtil = tokenUtil;
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
        this.cacheManager = cacheManager;
    }

    @PostMapping("/login")
    public Result<String> login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null) {
            return ResultUtil.error(ResultEnum.ACCOUNT_NOT_EXIST);
        }
        if (passwordEncoder.matches(password, userDetails.getPassword())) {
            String token = tokenUtil.createToken(userDetails.getUsername());
            Cache cache = cacheManager.getCache("user_authority");
            cache.put(userDetails.getUsername(), userDetails.getAuthorities());
            return ResultUtil.success(token);
        } else {
            return ResultUtil.error(ResultEnum.ERROR_PASSWORD);
        }
    }

}
